#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

class Base {
public:
    Base(const char * pbase)
    : _pbase(new char[strlen(pbase) + 1]())
    { 
        strcpy(_pbase,pbase);
        /* cout << "Base()" << endl; */ 
    }

    void display() const{
        cout << "_base:" << _pbase << endl;
    }

    ~Base(){ 
        if(_pbase){
            delete [] _pbase;
            _pbase = nullptr;
        }
        /* cout << "~Base()" << endl; */ 
    }

    Base(const Base & rhs)
    : _pbase(new char[strlen(rhs._pbase) + 1]())
    {
        strcpy(_pbase,rhs._pbase);
    }

    Base & operator=(const Base & rhs){
        if(this != &rhs){
            delete [] _pbase;
            _pbase = new char[strlen(rhs._pbase) + 1]();
            strcpy(_pbase,rhs._pbase);
        }
        return *this;
    }

    char * _pbase;
};


class Derived
: public Base 
{
public:
    Derived(const char * pbase,const char * pderived)
    : Base(pbase)//显式调用基类的构造函数
    , _pderived(new char[strlen(pderived) + 1]())
    { 
        strcpy(_pderived,pderived);
        /* cout << "Derived(long)" << endl; */
    }

    ~Derived(){ 
        if(_pderived){
            delete [] _pderived;
            _pderived = nullptr;
        }
        /* cout << "~Derived()" << endl; */ 
    }

#if 1
    Derived(const Derived & rhs)
    : Base(rhs) //显式调用Base的拷贝构造
    , _pderived(new char[strlen(rhs._pderived) + 1]())
    { 
        strcpy(_pderived,rhs._pderived);
        cout << "Derived(const Derived &)" << endl;
    }


    Derived & operator=(const Derived & rhs){
        if(this != &rhs){
            //需要显式调用Base的赋值运算符函数
            Base::operator=(rhs);
            delete [] _pderived;
            _pderived = new char[strlen(rhs._pderived) + 1]();
            strcpy(_pderived,rhs._pderived);
            cout << "Derived& operator=(const Derived&)" << endl;
        }
        return *this;
    }
#endif

    void display() const{
        Base::display();
        cout << "_derived:" << _pderived << endl; 
    }

    char * _pderived;
};

void test0(){
    Derived d1("hello","world");
    Derived d2 = d1;
    d2.display();

    d2 = d1;

    Derived d3("beijing","shanghai");
    d3  = d1;
    d3.display();
}


int main(void){
    test0();
    return 0;
}
